# -*- coding:utf-8 -*-
"""
# Session配置：
# Session类型>>>cache/redis/memcached
# ====================
# memcache连接配置
# conn = memcache.Client(['192.168.42.134:12000'], debug=True)
# redis连接配置
# pool = redis.ConnectionPool(host='192.168.42.134', port=6379)
# conn = redis.Redis(connection_pool=pool)
# 默认连接配置
conn = None
# Session类型
SESSION_TYPE = 'cache'
# Session超时时间（秒）
SESSION_EXPIRES = 60
"""
from toTest import settings
from hashlib import sha1
import os
import time
import json

create_session_id = lambda: sha1('{}{}'.format (os.urandom(16), time.time())).hexdigest()
# create_session_id = lambda: sha1(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf-8')).hexdigest()  # py3


class SessionFactory:

	@staticmethod
	def get_session_obj(handler):
		obj = None

		if settings.SESSION_TYPE == "cache":
			obj = CacheSession(handler)
		elif settings.SESSION_TYPE == "memcached":
			obj = MemcachedSession(handler)
		elif settings.SESSION_TYPE == "redis":
			obj = RedisSession(handler)
		return obj


class CacheSession:
	session_container = {}

	def __init__(self, handler, session_id='__kckckc__'):
		self.handler = handler
		self.session_id = session_id
		client_random_str = handler.get_cookie(self.session_id, None)
		if client_random_str and client_random_str in CacheSession.session_container:
			self.random_str = client_random_str
		else:
			self.random_str = create_session_id()
			CacheSession.session_container[self.random_str] = {}

		expires_time = time.time() + settings.SESSION_EXPIRES
		handler.set_cookie(self.session_id, self.random_str, expires=expires_time)

	def __getitem__(self, key):
		ret = CacheSession.session_container[self.random_str].get(key, None)
		return ret

	def __setitem__(self, key, value):
		CacheSession.session_container[self.random_str][key] = value

	def __delitem__(self, key):
		if key in CacheSession.session_container[self.random_str]:
			del CacheSession.session_container[self.random_str][key]


class MemcachedSession:
	mc = settings.conn

	def __init__(self, handler, session_id='__kckckc__'):
		self.handler = handler
		self.session_id = session_id
		# 从客户端获取随机字符串
		client_random_str = handler.get_cookie(self.session_id, None)
		# 如果从客户端获取到了随机字符串
		# 客户端存在并在服务端也存在
		if client_random_str and MemcachedSession.mc.get(client_random_str):
			self.random_str = client_random_str
		else:
			self.random_str = create_session_id()
			MemcachedSession.mc.set(self.random_str, json.dumps({}), settings.SESSION_EXPIRES)

		# 若多次进入，则需更新超时时间，即重新设置获取值、超时时间
		MemcachedSession.mc.set(self.random_str, MemcachedSession.mc.get(self.random_str), settings.SESSION_EXPIRES)

		expires_time = time.time() + settings.SESSION_EXPIRES
		handler.set_cookie(self.session_id, self.random_str, expires=expires_time)

	def __getitem__(self, key):
		ret = MemcachedSession.mc.get(self.random_str)
		ret_dic = json.loads(ret)
		result = ret_dic.get(key, None)
		return result

	def __setitem__(self, key, value):
		ret = MemcachedSession.mc.get(self.random_str)
		ret_dic = json.loads(ret)
		ret_dic[key] = value
		MemcachedSession.mc.set(self.random_str, json.dumps(ret_dic), settings.SESSION_EXPIRES)

	def __delitem__(self, key):
		ret = MemcachedSession.mc.get(self.random_str)
		ret_dic = json.loads(ret)
		del ret_dic[key]
		MemcachedSession.mc.set(self.random_str, json.dumps(ret_dic), settings.SESSION_EXPIRES)


class RedisSession:
	r = settings.conn

	def __init__(self, handler, session_id='__kckckc__'):
		self.handler = handler
		self.session_id = session_id
		# 从客户端获取随机字符串
		client_random_str = handler.get_cookie(self.session_id, None)
		# 如果从客户端获取到了随机字符串
		# 客户端存在并在服务端也存在
		if client_random_str and RedisSession.r.exists(client_random_str):
			self.random_str = client_random_str
		else:
			self.random_str = create_session_id()
			RedisSession.r.hset(self.random_str, None, None)
		# 若多次进入，则需更新超时时间，即重新设置获取值、超时时间
		RedisSession.r.expire(self.random_str, settings.SESSION_EXPIRES)

		expires_time = time.time() + settings.SESSION_EXPIRES
		handler.set_cookie(self.session_id, self.random_str, expires=expires_time)

	def __getitem__(self, key):
		result = RedisSession.r.hget(self.random_str, key)
		if result:
			ret_str = result.decode('utf-8')
			try:
				result = json.loads(ret_str)
			except:
				result = ret_str
			return result
		else:
			return result

	def __setitem__(self, key, value):
		if type(value) == dict:
			RedisSession.r.hset(self.random_str, key, json.dumps(value))
		else:
			RedisSession.r.hset(self.random_str, key, value)

	def __delitem__(self, key):
		RedisSession.r.hdel(self.random_str, key)

